define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index  : function () {
        // 初始化表格参数配置
            Table.api.init();

            //绑定事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var panel = $($(this).attr("href"));
                if (panel.length > 0) {
                    Controller.table[panel.attr("id")].call(this);
                    $(this).on('click', function (e) {
                        $($(this).attr("href")).find(".btn-refresh").trigger("click");
                    });
                }
                //移除绑定的事件
                $(this).unbind('shown.bs.tab');
            });

            //必须默认触发shown.bs.tab事件
            $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");
            let q = {}
            location.search.replace(/([^?&=]+)=([^&]+)/g,function(_,k,v){q[k]=v});
            if (q.active) {
                $('ul.nav-tabs li .'+q.active).trigger("click");
            }
            $(document).on('click', '.show-detail', function (data) {
                var area = ['95%', '95%'];
                var options = {
                    shadeClose : false,
                    shade      : [0.3, '#393D49'],
                    area       : area,
                    callback   : function (value) {
                        //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
                        console.log(value);
                    }
                };
                Fast.api.open($.fn.bootstrapTable.defaults.extend.detail_url + "?ids=" + $(this).data('id'), '合同', options);
            }).on('click', '.show-customer', function (data) {
                var area = ['95%', '95%'];
                var options = {
                    shadeClose : false,
                    shade      : [0.3, '#393D49'],
                    area       : area,
                    callback   : function (value) {
                        //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
                        console.log(value);
                    }
                };
                Fast.api.open("qingdongwms/customer/customer/detail?ids=" + $(this).data('id'), '客户详情', options);
            }).on("click", ".btn-export", function () {
                var tab_id=$('.active.in').attr('id');
                var table,type;
                switch (tab_id){
                    case 'first'://全部
                        table=$('#table');
                        type=0;
                        break;
                    case 'second'://我负责的
                        table=$('#table1');
                        type=1;
                        break;
                    case 'third'://下属负责的
                        table=$('#table2');
                        type=2;
                        break;
                    case 'four'://今日待跟进
                        table=$('#table3');
                        type=3;
                        break;
                    case 'five'://今日已跟进
                        table=$('#table4');
                        type=4;
                        break;
                    case 'six'://从未跟进的
                        table=$('#table5');
                        type=5;
                        break;
                }

                var ids = Table.api.selectedids(table);
                var page = table.bootstrapTable('getData');
                var options = table.bootstrapTable('getOptions');
                var params=options.queryParams({});
                var all = options.totalRows;
                var sort = options.sortName+' '+options.sortOrder;
                var filter = params.filter;
                var op = params.op;
                Layer.confirm("请选择导出的选项", {
                    title   : '导出数据',
                    btn     : ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
                    success : function (layero, index) {
                        $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
                    }, yes   : function (index, layero) {
                        if (ids.length == 0) {
                            Layer.alert('数据为空');
                            return true;
                        }
                        $.post('qingdongwms/customer/contract/export', {sort:sort,ids : ids.join(","), isall : 1}, function (res) {
                            if(res.code == 1){
                                Layer.alert(res.msg);
                                window.location.href = res.data.filePath;
                                Layer.close(index);
                                table.bootstrapTable('refresh');
                            }else{
                                Layer.alert(res.msg);
                            }
                        }, 'json');
                        return false;
                    },
                    btn2    : function (index, layero) {
                        if (page.length == 0) {
                            Layer.alert('数据为空');
                            return true;
                        }
                        var ids = [];
                        $.each(page, function (i, j) {
                            ids.push(j.id);
                        });
                        $.post('qingdongwms/customer/contract/export', {sort:sort,ids : ids.join(","), isall : 2}, function (res) {
                            if(res.code == 1){
                                Layer.alert(res.msg);
                                window.location.href = res.data.filePath;
                                Layer.close(index);
                                table.bootstrapTable('refresh');
                            }else{
                                Layer.alert(res.msg);
                            }
                        }, 'json');
                        return false;
                    },
                    btn3    : function (index, layero) {
                        if (page.length == 0) {
                            Layer.alert('数据为空');
                            return true;
                        }
                        $.post('qingdongwms/customer/contract/export?filter='+filter+'&op='+op, {sort:sort,ids : ids.join(","), isall : 3,type:type}, function (res) {
                            if(res.code == 1){
                                Layer.alert(res.msg);
                                window.location.href = res.data.filePath;
                                Layer.close(index);
                                table.bootstrapTable('refresh');
                            }else{
                                Layer.alert(res.msg);
                            }
                        }, 'json');
                        return false;
                    }
                })
            }).on('click','.btn-imports',function () {
                Fast.api.open("qingdongwms/customer/contract/import", "合同导入",{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    'area':[
                        $(window).width() > 800 ? '600px' : '400px',
                        $(window).height() > 600 ? '500px' : '400px'
                    ],
                    callback:function(value){
                        Form.events.plupload("#plupload-local");

                        //   在这里可以接收弹出层中使用`Fast.api.close(data)`进行回传数据
                    },
                });

            }).on("click", ".btn-export-product", function () {

                var tab_id=$('.active.in').attr('id');
                var table;
                switch (tab_id){
                    case 'first'://全部
                        table=$('#table');
                        break;
                    case 'second'://我负责的
                        table=$('#table1');
                        break;
                    case 'third'://下属负责的
                        table=$('#table2');
                        break;
                    case 'four'://今日待跟进
                        table=$('#table3');
                        break;
                    case 'five'://今日已跟进
                        table=$('#table4');
                        break;
                    case 'six'://从未跟进的
                        table=$('#table5');
                        break;
                }
                var ids = Table.api.selectedids(table);
                var page = table.bootstrapTable('getData');
                var all = table.bootstrapTable('getOptions').totalRows;
                var search = $("form.form-commonsearch").serialize();
                var sort = table.bootstrapTable('getOptions').sortName+' '+table.bootstrapTable('getOptions').sortOrder;
                var filter = search.filter;
                var op = search.op;
                Layer.confirm("请选择导出的选项", {
                    title   : '导出产品明细数据',
                    btn     : ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
                    success : function (layero, index) {
                        $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
                    }, yes   : function (index, layero) {
                        if (ids.length == 0) {
                            Layer.alert('数据为空');
                            return true;
                        }
                        $.post('qingdongwms/customer/contract/export_product', {sort:sort,ids : ids.join(","), type : 1, filter:filter,op:op, status : page[0]['status']}, function (res) {
                            Layer.alert(res.msg);
                            if(res.code == 1){
                                window.location.href = res.data.filePath;
                                Layer.close(index);
                            }
                            table.bootstrapTable('refresh');
                        }, 'json');
                        return false;
                    },
                    btn2    : function (index, layero) {
                        if (page.length == 0) {
                            Layer.alert('数据为空');
                            return true;
                        }
                        var ids = [];
                        $.each(page, function (i, j) {
                            ids.push(j.id);
                        });
                        $.post('qingdongwms/customer/contract/export_product', {sort:sort,ids : ids.join(","), type : 2, filter:filter,op:op, status : page[0]['status']}, function (res) {
                            Layer.alert(res.msg);
                            if(res.code == 1){
                                window.location.href = res.data.filePath;
                                Layer.close(index);
                            }
                            table.bootstrapTable('refresh');
                        }, 'json');
                        return false;
                    },
                    btn3    : function (index, layero) {
                        if (page.length == 0) {
                            Layer.alert('数据为空');
                            return true;
                        }
                        $.post('qingdongwms/customer/contract/export_product', {sort:sort,ids : ids.join(","), type : 3, filter:filter,op:op, status : page[0]['status']}, function (res) {
                            Layer.alert(res.msg);
                            if(res.code == 1){
                                window.location.href = res.data.filePath;
                                Layer.close(index);
                            }
                            table.bootstrapTable('refresh');
                        }, 'json');
                        return false;
                    }
                })
            }).on('click','.btn-imports-product',function () {
                Fast.api.open("qingdongwms/customer/contract/import_product", "合同导入产品明细",{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    'area':[
                        $(window).width() > 800 ? '600px' : '400px',
                        $(window).height() > 600 ? '500px' : '400px'
                    ],
                    callback:function(value){
                        Form.events.plupload("#plupload-local");

                        //   在这里可以接收弹出层中使用`Fast.api.close(data)`进行回传数据
                    },
                });

            }).on("click", ".export_pdfs",function(data){
                var tab_id=$('.active.in').attr('id');
                var table;
                switch (tab_id){
                    case 'first'://全部
                        table=$('#table');
                        break;
                    case 'second'://我负责的
                        table=$('#table1');
                        break;
                    case 'third'://下属负责的
                        table=$('#table2');
                        break;
                    case 'four'://今日待跟进
                        table=$('#table3');
                        break;
                    case 'five'://今日已跟进
                        table=$('#table4');
                        break;
                    case 'six'://从未跟进的
                        table=$('#table5');
                        break;
                }
                var ids=Table.api.selectedids(table);
                if(ids == false){
                    Layer.alert('请先选择合同');
                    return false;
                }
                if(ids.length > 10){
                    Layer.alert('一次性最多下载10份合同');
                    return false;
                }
                $.each(ids,function (index,id){
                    Fast.api.ajax("qingdongwms/customer/contract/download_quote?id="+id,function(data,ret){
                        if(ret.code == 1){
                            const aEl = document.createElement('a');
                            aEl.target = '_blank';
                            aEl.href = data.file;
                            aEl.download = data.filename;
                            aEl.click();
                        }
                    },function(data,ret){
                    });

                })
            });


        },
        tableinfo:{
            url          : '',
            toolbar: '#toolbar',
            pk           : 'id',
            sortName     : 'id',
            fixedColumns : true,
            fixedNumber  : 1,
            fixedRightNumber  : 1,
            columns      : [
                [
                    {checkbox : true},
                    {
                        field : 'num', title : '合同编号', fixedColumns : true, formatter : function (value, row, index) {

                            if(value ==''){
                                value = '无';
                            }
                            return "<a href='javascript:void(0);' data-id='" + row.id + "' class='show-detail'>" + value + "</a>";
                        },operate:'like'
                    },
                    {
                        field : 'name', title : '合同名称', fixedColumns : true, formatter : function (value, row, index) {
                            if(value ==''){
                                value = '无';
                            }
                            return value;
                        },operate:false
                    },
                    {field : 'customer', title : '客户名称', formatter : function (value, row, index) {
                            if(row.customer){
                                return "<a href='javascript:void(0);' data-id='" + row.customer_id + "' class='show-customer'>" + row.customer.name + "</a>";
                            }
                            return '';
                        },operate:false},
                    {field : 'customer_id', title : '客户名称', visible: false, addClass: "selectpage", extend: "data-source='qingdongwms/customer/customer/index' data-field='name'"},
                    {field : 'receivables', title : '回款金额',formatter : function (value, row, index) {
                            if(row.receivables){
                                return row.receivables.repayment_money;
                            }
                            return 0;
                        },operate:false},
                    {field : 'invoice', title : '发票金额',formatter : function (value, row, index) {
                            if(row.invoice){
                                return row.invoice.invoice_money;
                            }
                            return 0;
                        },operate:false},
                    {field : 'contacts.name', title : '客户签约人',operate:false},
                    {field : 'order_staff.name', title : '公司签约人',operate:false},
                    {field : 'contract_status', title : '合同状态',operate:'=',searchList:{0:'进行中',1:'已完成',2:'已作废'},formatter:Table.api.formatter.status},
                    {field : 'check_status', title : '审核状态',formatter:Table.api.formatter.status, searchList: {0:'待审核', 1: '审核中',2:'审核通过',3:"审核未通过",4:"已撤销",9:'作废'},custom: {0: 'gray', 1: 'gray',2: 'success', 3: 'danger', 4: 'danger', 9: 'danger'}},
                    {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                    {field : 'updatetime', title : '更新时间',operate:false},
                    {
                        field: 'operate2',operate:false, title: __('Operate'), events: {
                            'click .btn-chooseone': function (e, value, row, index) {
                                Fast.api.close({id: row.id, name: row.name, money: row.money});
                            },
                        }, formatter: function () {
                            return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                        }
                    },
                    {
                        field: 'operate', title: __('Operate'),  events: Table.api.events.operate, formatter: Table.api.formatter.buttons,
                        buttons: [
                            {
                                name: 'detail',
                                text: __('跟进'),
                                title: __('跟进'),
                                extend:'data-area=["80%","80%"]',
                                classname: 'records btn-dialog',
                                url: 'qingdongwms/contract/record/add',
                                visible: function (row) {
                                    //返回true时按钮显示,返回false隐藏
                                    return true;
                                },
                            },
                            {
                                name: 'detail',
                                text: __('回款'),
                                title: __('回款'),
                                extend:'data-area=["90%","90%"]',
                                classname: 'records btn-dialog',
                                url: 'qingdongwms/customer/receivables/add/customer_id/{customer_id}/contract_id/{id}',
                                visible: function (row) {
                                    //返回true时按钮显示,返回false隐藏
                                    return true;
                                }
                            }
                        ]
                    }

                ]
            ],
            pagination        : true,
            search            : false,
            commonSearch      : true,
            searchFormVisible : true,
            //显示导出按钮
            showExport: false,
            onLoadSuccess:function(){
                // 这里就是数据渲染结束后的回调函数
                $(".btn-add").data("area",["95%","95%"]);
                $(".btn-edit").data("area",["95%","95%"]);
            }
        },
        table: {
            first: function () {
                // 初始化表格参数配置
                Table.api.init({
                    extend : {
                        add_url    : 'qingdongwms/customer/contract/add',
                        detail_url : 'qingdongwms/customer/contract/detail',
                        table      : 'contract',
                    }
                });
                if(Config.fields !='[]'){
                    if (Config.fields && Object.keys(Config.fields).length > 0) {
                        var fields = JSON.parse(Config.fields);
                        var start = Controller.tableinfo.columns[0].length-10;
                        for (var i = 0; i < fields.length; i++) {
                            if (fields[i].hasOwnProperty('formatter'))
                                fields[i].formatter = eval(fields[i].formatter);
                            if (fields[i].hasOwnProperty('events'))
                                fields[i].events = eval(fields[i].events);
                            if (fields[i].hasOwnProperty('searchList'))
                                fields[i].searchList = JSON.parse(fields[i].searchList);
                            Controller.tableinfo.columns[0].splice(start + i, 0, fields[i]);
                        }
                    }

                }
                const q = {};
                location.search.replace(/([^?&=]+)=([^&]+)/g,function(_,k,v){q[k]=v});

                var table = $("#table");
                Controller.tableinfo.url=location.href+'&type=0';
                Controller.tableinfo.toolbar='#toolbar';
                Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length-1].table=table;
                if (q.isselect == 1) {
                    Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length - 1].visible = false;
                } else {
                    Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length - 2].visible = false;
                }
                // 初始化表格
                table.bootstrapTable(Controller.tableinfo);
                // 为表格绑定事件
                Table.api.bindevent(table);
            },
            second: function () {
                // 初始化表格参数配置
                Table.api.init({
                    extend : {
                        add_url    : 'qingdongwms/customer/contract/add',
                        detail_url : 'qingdongwms/customer/contract/detail',
                        table      : 'contract',
                    }
                });


                var table = $("#table1");
                Controller.tableinfo.url=location.href+'&type=1';
                Controller.tableinfo.toolbar='#toolbar1';
                Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length-1].table=table;
                // 初始化表格
                table.bootstrapTable(Controller.tableinfo);

                // 为表格绑定事件
                Table.api.bindevent(table);
            },
            third: function () {
                // 初始化表格参数配置
                Table.api.init({
                    extend : {
                        add_url    : 'qingdongwms/customer/contract/add',
                        detail_url : 'qingdongwms/customer/contract/detail',
                        table      : 'contract',
                    }
                });

                var table = $("#table2");
                Controller.tableinfo.url=location.href+'&type=2';
                Controller.tableinfo.toolbar='#toolbar2';
                Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length-1].table=table;
                // 初始化表格
                table.bootstrapTable(Controller.tableinfo);

                // 为表格绑定事件
                Table.api.bindevent(table);
            },
            four: function () {
                // 初始化表格参数配置
                Table.api.init({
                    extend : {
                        add_url    : 'qingdongwms/customer/contract/add',
                        detail_url : 'qingdongwms/customer/contract/detail',
                        table      : 'contract',
                    }
                });

                var table = $("#table3");
                Controller.tableinfo.url=location.href+'&type=3';
                Controller.tableinfo.toolbar='#toolbar3';
                Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length-1].table=table;
                // 初始化表格
                table.bootstrapTable(Controller.tableinfo);

                // 为表格绑定事件
                Table.api.bindevent(table);
            },
            five: function () {
                // 初始化表格参数配置
                Table.api.init({
                    extend : {
                        add_url    : 'qingdongwms/customer/contract/add',
                        detail_url : 'qingdongwms/customer/contract/detail',
                        table      : 'contract',
                    }
                });

                var table = $("#table4");
                Controller.tableinfo.url=location.href+'&type=4';
                Controller.tableinfo.toolbar='#toolbar4';
                Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length-1].table=table;
                // 初始化表格
                table.bootstrapTable(Controller.tableinfo);

                // 为表格绑定事件
                Table.api.bindevent(table);
            },
            six: function () {
                // 初始化表格参数配置
                Table.api.init({
                    extend : {
                        add_url    : 'qingdongwms/customer/contract/add',
                        detail_url : 'qingdongwms/customer/contract/detail',
                        table      : 'contract',
                    }
                });


                var table = $("#table5");
                Controller.tableinfo.url=location.href+'&type=5';
                Controller.tableinfo.toolbar='#toolbar5';
                Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length-1].table=table;
                // 初始化表格
                table.bootstrapTable(Controller.tableinfo);

                // 为表格绑定事件
                Table.api.bindevent(table);
            },
        },
        add    : function () {
            Controller.api.bindevent();
        },
        edit    : function () {
            Controller.api.bindevent();
        },
        quote_change    : function () {
            Controller.api.bindevent();
        },
        address    : function () {
            Controller.api.bindevent();
        },
        invoice_contract    : function () {
            Controller.api.bindevent();
        },
        receipt_contract    : function () {
            Controller.api.bindevent();
        },
        import  : function () {
            Form.api.bindevent($("form[role=form]"), function (data, ret) {
                //这里是表单提交处理成功后的回调函数，接收来自php的返回数据
                Fast.api.close(data);//这里是重点
            }, function (data, ret) {
                Toastr.error(ret.msg);
                return false;
            });
        },
        import_product  : function () {
            Form.api.bindevent($("form[role=form]"), function (data, ret) {
                //这里是表单提交处理成功后的回调函数，接收来自php的返回数据
                Fast.api.close(data);//这里是重点
            }, function (data, ret) {
                Toastr.error(ret.msg);
                return false;
            });
        },

        words  : function () {
            $('.copy').on('click',function (){
                var copyhtml=$(this).prev().html();
                let copyInput = document.createElement('input');//创建input元素
                document.body.appendChild(copyInput);//向页面底部追加输入框
                copyInput.setAttribute('value', copyhtml);//添加属性，将url赋值给input元素的value属性
                copyInput.select();//选择input元素
                document.execCommand("Copy");//执行复制命令
                Layer.msg('复制成功！');
                copyInput.remove();//删除动态创建的节点

            })
            $("[name='is_template']").on('click',function (){
                var ischecked=$(this).is(':checked');
                if(ischecked == true){
                    $('#template_name').show();
                }else{
                    $('#template_name').hide();
                }
            })
            $("[name='template_id']").on('change',function (){
                var url=$(this).find(':selected').data('url');
                $('#file').val(url)
            })
            Form.api.bindevent($("form[role=form]"), function (data, ret) {
                Fast.api.close(data);//这里是重点
            }, function (data, ret) {
                Toastr.error(ret.msg);
                return false;
            });
        },
        tabledetail    : {
            record: function () {

                //跟进记录
                var table1 = $("#records");
                // 初始化表格
                table1.bootstrapTable({
                    url          : 'qingdongwms/customer/record/index?contract_id='+Config.idinfo.id,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar: "#toolbar_records",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {field: 'follow_type', title: __('跟进类型')},
                            {field: 'follow_time', title: __('跟进时间')},
                            {field: 'follow', title: __('跟进状态')},
                            {field: 'content', title: __('跟进内容'),cellStyle:function (value,row,index,field) {
                                    return {
                                        css: {
                                            "min-width": "150px",
                                            "white-space": "nowrap",
                                            "text-overflow": "ellipsis",
                                            "overflow": "hidden",
                                            "max-width":"300px",
                                            'cursor':"pointer"
                                        }
                                    };
                                },formatter:function (value,row,index,field) {
                                    var span=document.createElement('span');
                                    span.setAttribute('title',value);
                                    span.innerHTML = value;
                                    return span.outerHTML;
                                }
                            },
                            {field: 'next_time', title: __('下次跟进时间')},
                            {
                                field     : 'operate',
                                title     : __('Operate'),
                                table     : table1,
                                events    : Table.api.events.operate,
                                formatter : Table.api.formatter.operate,
                                buttons   : [
                                    {
                                        name      : '详情',
                                        text      : __('详情'),
                                        classname : 'records btn-dialog',
                                        url       : 'qingdongwms/customer/record/detail',
                                        callback: function (data) {
                                            $('.btn-success').trigger('click');
                                        },

                                    },
                                    {
                                        name      : '评论',
                                        text      : __('评论'),
                                        classname : 'records btn-dialog',
                                        url       : 'qingdongwms/customer/comment/add',
                                        callback: function (data) {

                                        },

                                    }
                                ]
                            }
                        ]
                    ]
                });
                Table.api.bindevent(table1);
            },
            settings2: function () {
                //回款计划
                var table_plan=$('#plan');
                table_plan.bootstrapTable({
                    url          : 'qingdongwms/customer/contract/get_receivables_plan' + location.search,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar: "#toolbar_receivablesplan",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {field : 'num', title : '期数'},
                            {field : 'money', title : '计划回款金额'},
                            {field : 'return_date', title : '计划回款日期'},
                            {field : 'return_type', title : '计划回款方式'},
                            {field : 'remind', title : '提前几日提醒'},
                            {field : 'remarks', title : '备注'},
                        ]
                    ]
                });
                Table.api.bindevent(table_plan);
                //回款记录
                var table_receivables=$('#receivables');
                table_receivables.bootstrapTable({
                    url          : 'qingdongwms/customer/contract/get_receivables' + location.search,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar: "#toolbar_receivables",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {field : 'number', title : '回款编号',
                                formatter: function (value, row, index) {

                                    return "<a href='javascript:void(0);' class='btn-dialog' " +
                                        "data-url='qingdongwms/customer/receivables/detail/ids/"+row.id+"' data-shade='0.3' data-title='回款详情' >" + value + "</a>";
                                }
                            },
                            {field : 'money', title : '回款金额'},
                            {field : 'owner_staff.name', title : '负责人'},
                            {
                                field      : 'check_status', title : '状态', formatter : Table.api.formatter.status,
                                searchList : {0 : '待审核', 1 : '审核中', 2 : '审核通过', 3 : '审核未通过', 4 : '撤销', 5 : '草稿(未提交)'},
                                custom: {0: 'gray', 1: 'gray',2: 'success', 3: 'danger', 4: 'danger', 5: 'danger'}
                            },
                            {field : 'return_time', title : '回款日期'},
                        ]
                    ]
                });
                Table.api.bindevent(table_receivables);
            },
            settings4: function () {

                //操作日志
                var table2 = $("#operation_log");
                // 初始化表格
                table2.bootstrapTable({
                    url          : 'qingdongwms/customer/log/index?contract_id='+Config.idinfo.id,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar: "#toolbar_log",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {field: 'staff.name', title: __('员工')},
                            {field: 'content', title: __('内容'),cellStyle:function (value,row,index,field) {
                                    return {
                                        css: {
                                            "min-width": "150px",
                                            "white-space": "nowrap",
                                            "text-overflow": "ellipsis",
                                            "overflow": "hidden",
                                            "max-width":"300px",
                                            'cursor':"pointer"
                                        }
                                    };
                                },formatter:function (value,row,index,field) {
                                    var span=document.createElement('span');
                                    span.setAttribute('title',value);
                                    span.innerHTML = value;
                                    return span.outerHTML;
                                }
                            },
                            {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},

                        ]
                    ]
                });
                Table.api.bindevent(table2);
            },
            basic:function (){

            },
            other:function (){

            },
            product: function () {

                //操作日志
                var table2 = $("#operation_product");
                // 初始化表格
                table2.bootstrapTable({
                    url          : 'qingdongwms/customer/contract/get_contract_product?contract_id='+Config.idinfo.id,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar: "#toolbar_product",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {field: 'productinfo.name', title: __('产品名称')},
                            {field: 'productinfo.unit', title: __('单位')},
                            {field: 'number', title: __('数量')},
                            {field: 'price', title: __('销售单价（元）')},
                            {field: 'productinfo.wholesale', title: __('批发价（元）')},
                            {field: 'total_price', title: __('销售价格小计（元）'), formatter : function (value, row, index) {

                                    return row.price * row.number;
                                }},

                            // {field: 'ship_status', title: __('发货状态'),formatter:Table.api.formatter.status, searchList: {0:'待发货', 1: '已发货',2:'已收货'}},
                        ]
                    ]
                });
                Table.api.bindevent(table2);
            },
        },
        detail : function () {
            // 初始化表格参数配置
            Table.api.init({});
            $('.stafflist').popover({
                placement : 'bottom',
                trigger : 'hover'
            });
            //绑定事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var panel = $($(this).attr("href"));
                if (panel.length > 0) {
                    Controller.tabledetail[panel.attr("id")].call(this);
                    $(this).on('click', function (e) {
                        $($(this).attr("href")).find(".btn-refresh").trigger("click");
                    });
                }
                //移除绑定的事件
                $(this).unbind('shown.bs.tab');
            });

            //必须默认触发shown.bs.tab事件
            $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");

            //附件
            var table_files=$('#files');
            table_files.bootstrapTable({
                url          : 'qingdongwms/customer/contract/get_file'+ location.search,
                pk           : 'id',
                sortName     : 'id',
                toolbar: "#toolbar_files",
                operate      : false,
                commonSearch : false,
                search       : false,
                visible      : false,
                showColumns  : false,
                showExport   : false,
                showToggle   : false,
                columns      : [
                    [
                        {field : 'name', title : '附件名称'},
                        {field : 'size', title : '附件大小'},
                        {
                            field : 'file_path', title : '文件预览', events : Table.api.events.image, formatter : Table.api.formatter.image, operate : false
                        },

                    ]
                ]
            });
            Table.api.bindevent(table_files);
            //编辑
            $(document).on('click','#edits',function () {
                var id=$('#contractId').val();
                Fast.api.open("qingdongwms/customer/contract/edit?ids="+id, "合同编辑",{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    area:["95%","95%"],
                    callback:function(value){
                        location.reload();
                    },
                });

            }).on('click', '.btn-word', function (data) {
                //导出word
                var area = [$(window).width() > 1200 ? '1200px' : '70%', $(window).height() > 800 ? '800px' : '80%'];
                var options = {
                    shadeClose : false,
                    shade      : [0.3, '#393D49'],
                    area       : area,
                    callback   : function (value) {
                        //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
                        window.location.href = value.file;
                    }
                };
                Fast.api.open("qingdongwms/customer/contract/words?ids=" + $(this).data('id'), '导出word', options);
            }).on('click','.btn-address',function () {
                var id=$('#contractId').val();
                Fast.api.open("qingdongwms/customer/contract/address?ids="+id, "填写收货地址",{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    area:["90%","90%"],
                    callback:function(value){
                        location.reload();
                    },
                });

            }).on('click','.btn-logistics',function () {
                var id=$('#contractId').val();
                Fast.api.open("qingdongwms/customer/contract/invoice_contract?ids="+id, "填写发票物流",{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    area:["90%","90%"],
                    callback:function(value){
                        location.reload();
                    },
                });

            }).on('click','.btn-receipt',function () {
                var id=$('#contractId').val();
                Fast.api.open("qingdongwms/customer/contract/receipt_contract?ids="+id, "填写发票回执单",{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    area:["90%","90%"],
                    callback:function(value){
                        location.reload();
                    },
                });

            });
            //删除
            $("#dels").on('click',function(){
                var id=$('#contractId').val();
                Layer.confirm('确定删除合同吗？', {
                    btn: ['确定','取消']
                },function(index, layero){
                    Fast.api.ajax("qingdongwms/customer/contract/del?ids="+id,function(data,ret){
                        if(ret.code == 1){
                            Layer.close(index);
                            parent.location.reload();
                        }
                    },function(data,ret){
                    });

                });
            });
            $(".btn-stop").on("click", function(res){
                var id = $('#contractId').val();
                Layer.confirm('确定要终止当前合同吗？', {
                    btn: ['确定','取消'],
                    title: '提示',
                },function(index, layero){
                    Fast.api.ajax("qingdongwms/customer/contract/revoke_contract?id="+id,function(data,ret){
                        if(ret.code == 1){
                            Layer.close(index);
                            location.reload();
                        }
                    },function(data,ret){
                    });
                });

            });
            Controller.api.bindevent();
        },
        api    : {
            bindevent : function () {
                $(document).on("fa.event.appendfieldlist", '.fieldlist', function(){
                    //通用的表单组件事件绑定和组件渲染
                    Form.events.selectpage($("form"));
                    Form.events.datetimepicker($("form"));
                });
                $(".selectpage").data("params", function (obj) {
                    var customer_id=$('#customer').val()
                    //obj为SelectPage对象
                    return {ids: customer_id};
                });

                function set_money(){
                    var $price = $('.price');
                    var $number = $('.number');
                    var price=0;
                    $.each($price, function (index, item) {
                        var p = $(item).val(), n = $number.eq(index).val();
                        p = parseFloat(p);
                        n = parseInt(n);
                        price += p * n;
                    });
                    $('#c-money').val(price);
                }
                $(document).on("change", ".product", function(){
                    var $this=$(this);
                    var id=$this.next('input').val();
                    Fast.api.ajax("qingdongwms/customer/contract/get_product_price?id="+id,function(data,ret){
                        $this.parent().parent().next('span').find('input').val(data.price);
                        set_money();
                        $(".fieldlist input:eq(2)").trigger("change");

                        return false;
                    });

                }).on("change", ".price", function(){
                    set_money();
                }).on("change", ".number", function(){
                    set_money();
                }).on("change", "#ratio_id", function(){
                    var ratio=$('#ratio_id').find('option:selected').data('ratio');
                    if(!ratio){
                        $('.table_ratio').hide();
                        return false;
                    }
                    var html="";
                    $.each(ratio,function (index,item){
                       html+="<tr>" +
                           "<td>"+item.ratio+"%<input type='hidden' name='row[ratios]["+index+"][ratio]' value='"+item.ratio+"'></td>" +
                           "<td><input data-source=\"qingdongwms/customer/customer/getteam\"" +
                           "class=\"form-control selectpage\" name=\"row[ratios]["+index+"][staff_id]\" placeholder=\"请选择团队成员\" type=\"text\" value=\"\"></td>" +
                           "</tr>";
                    });
                    $('.table_ratio').find('tbody').html(html);
                    $('.table_ratio').show();
                    Form.events.selectpage($("form"));

                    $(".selectpage").data("params", function (obj) {
                        var customer_id=$('[name="row[customer_id]"]').val()
                        if(!customer_id){
                            layer.msg('请先选择客户');
                            return false;
                        }
                        //obj为SelectPage对象
                        return {ids: customer_id};
                    });
                }).on("click", ".select-customer", function(){
                    var $this=$(this);
                    top.Fast.api.open($(this).data("url") , __('Select'), {callback: function (data) {
                            $this.html(data.name);
                            $('[name="'+$this.data('name')+'"]').val(data.id);
                    },area:["100%", "100%"]});
                }).on("click", ".select-contacts", function(){
                    var $this=$(this),customer_id=$('[name="row[customer_id]"]').val();
                    if(!customer_id){
                        Layer.msg('请先选择客户');
                        return false;
                    }
                    top.Fast.api.open($(this).data("url")+"&customer_id="+customer_id , __('Select'), {callback: function (data) {
                            $this.html(data.name);
                            $('[name="'+$this.data('name')+'"]').val(data.id);
                    },area:["100%", "100%"]});
                }).on("click", ".select-business", function(){
                    var $this=$(this),customer_id=$('[name="row[customer_id]"]').val();
                    if(!customer_id){
                        Layer.msg('请先选择客户');
                        return false;
                    }
                    top.Fast.api.open($(this).data("url")+"&customer_id="+customer_id , __('Select'), {callback: function (data) {
                            $this.html(data.name);
                            $('[name="'+$this.data('name')+'"]').val(data.id);
                            $.post('qingdongwms/customer/contract/get_business_product',{business_id:data.id},function (data){
                                if(data.code == 1){
                                    var result=[];
                                    $.each(data.data,function (index,params){
                                        var r={};
                                        if(params.productinfo){
                                            r.product_name=params.productinfo.name;
                                            r.type=params.productinfo.type;
                                            r.wholesale=params.productinfo.wholesale;
                                            if(params.productinfo.goods){
                                                r.goods_name=params.productinfo.goods.name;
                                            }
                                        }
                                        r.product_id=params.product_id;
                                        r.price=params.price;
                                        r.number=params.number;

                                        result.push(r);
                                    });
                                    var res=JSON.stringify(result);

                                    $('textarea[name="row[product]"]').val(res);
                                    $('.fieldlist').trigger("fa.event.refreshfieldlist");
                                    set_money();
                                }
                            },'json');
                    },area:["100%", "100%"]});
                }).on("click", ".select-product", function(){
                    var $this=$(this);
                    top.Fast.api.open($(this).data("url"), __('Select'), {callback: function (data) {
                            $this.html(data.name);
                            $('[name="'+$this.data('name')+'"]').val(data.id);
                            $this.parent().parent().next('td').find('input').val(data.price);
                            $this.parent().parent().parent().find('.price2').html(data.wholesale);
                            if(data.goods){
                                $this.parent().parent().parent().find('.goods').html(data.goods.name);
                            }
                            $this.parent().parent().parent().find('.type').html(data.type);


                            set_money();
                            $(".fieldlist input:eq(2)").trigger("change");
                    },area:["100%", "100%"]});
                });
                require(['backend/qingdongwms/common/common'])

                Form.api.bindevent($("form[role=form]"), function(data, ret){
                    //这里是表单提交处理成功后的回调函数，接收来自php的返回数据
                    Fast.api.close(data);//这里是重点
                });
            }
        }
    };
    return Controller;
});